package cn.yeziji.forum.listener.mq;

import cn.yeziji.forum.basic.netty.Message;
import cn.yeziji.forum.basic.netty.chat.ChatMessage;
import cn.yeziji.forum.common.key.ChatroomCacheKey;
import cn.yeziji.forum.common.key.MessageKey;
import cn.yeziji.forum.common.key.NoticeCacheKey;
import cn.yeziji.forum.common.key.RabbitMQConfig;
import cn.yeziji.forum.common.websocket.Chatroom;
import cn.yeziji.forum.dao.intf.ForumUserDao;
import cn.yeziji.forum.entity.ForumUserEntity;
import cn.yeziji.forum.service.PrivateChatService;
import cn.yeziji.forum.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 私聊聊天室
 *
 * <p>获取通信处理的数据，返回给客户端
 *
 * @author gzkemays
 * @since 2022/11/08 10:20 PM
 */
@Slf4j
@Component
@RabbitListener(queuesToDeclare = @Queue(RabbitMQConfig.PRIVATE_CHAT_MSG_DAO))
public class PrivateChatListener {
  @Resource RabbitTemplate rabbitTemplate;
  @Resource PrivateChatService privateChatService;
  @Resource RedisTemplate<String, Object> redisTemplate;
  @Resource ForumUserDao userDao;

  @RabbitHandler
  public void privateChat(ChatMessage message) {
    RedisUtils redisUtils = new RedisUtils(redisTemplate);
    ForumUserEntity userEntity = userDao.selectUserByNickName(message.getTo());
    String toUsername = userEntity.getUsername(), fromUsername = message.getFrom().getUsername();
    String chatroom = buildChatroom(toUsername, fromUsername);
    Message msg = new Message(MessageKey.PRIVATE_CHAT_FLAG);
    if (StringUtils.isBlank(message.getText())) {
      // 获取聊天信息
      List<ChatMessage> chatroomRecords = privateChatService.getChatroomRecords(chatroom);
      msg.json(chatroomRecords).currentDate().target(message.getFrom().getUsername());
      log.info(
          "获取 {} 和 {} 的聊天记录 --> {}",
          userEntity.getUsername(),
          message.getFrom().getUsername(),
          chatroomRecords);
      // 通知 netty 的消息队列
      rabbitTemplate.convertAndSend(
          RabbitMQConfig.PRIVATE_CHAT_MSG_EXCHANGE,
          RabbitMQConfig.PRIVATE_CHAT_MSG_ROUTING_KEY,
          msg);
      // 消除 unread 中 type = 1 的未读数数据

    } else {
      if (!message.isOnline()) {
        // 不在线，保存聊天记录
        log.warn("{} 不在线，保存至 unread", toUsername);
        msg.json(message).currentDate();
        redisUtils.listHeaderPushAll(NoticeCacheKey.UN_READ + toUsername, msg);
      }
      // 由于发送消息被 listener 监听到并有消息，所以直接构建 redis 聊天记录。
      redisUtils.listFooterPushAll(
          ChatroomCacheKey.ONLINE_PRIVATE_CHAT_KEY + buildChatroom(toUsername, fromUsername),
          message);
    }
  }

  private String buildChatroom(String to, String from) {
    String[] split = (to + Chatroom.AND + from).split(Chatroom.AND);
    Arrays.sort(split);
    return split[0] + Chatroom.AND + split[1];
  }
}
